'use strict';

/**
 * 权限验证中间件
 * @return {function}
 */

module.exports = () => {
  return async function(ctx, next) {
    const { request, session, app, logger } = ctx;
    try {
      const route = `${request.url.split('?')[0]},${request.method.toUpperCase()}`;
      const userAuth = JSON.parse(await app.redis.get('cache').get(session.uid));
      if (!userAuth.some(val => `${val.route},${val.method}` === route)) {
        ctx.status = 403;
        return;
      }
      await next();
    } catch (e) {
      logger.error(`权限获取异常: ${e}`);
    }
  };
};
